package com.zh.common.exception;

import com.alibaba.fastjson.JSON;
import com.zh.common.vo.ErrorResult;
import com.zh.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.http.HttpStatus;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
import java.io.IOException;
import java.util.List;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class ExceptionHandlerConfig {

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result handleBusinessException(ServiceException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(e.getCode());
        ErrorResult result = new ErrorResult(e.getCode(), rootMessage(e));
        log.info(JSON.toJSONString(result));
        return Result.failed(e.getMsg(), e.getMsgZh());
    }


    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ErrorResult handleBusinessException(BusinessException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(ErrorCode.UNKNOWNERROR.getCode());
        ErrorResult result = new ErrorResult(ErrorCode.UNKNOWNERROR.getCode(), rootMessage(e));
        log.info(JSON.toJSONString(result));
        return result;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ErrorResult handleIllegalArgumentException(IllegalArgumentException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(ErrorCode.UNKNOWNERROR.getCode());
        ErrorResult result = new ErrorResult(ErrorCode.UNKNOWNERROR.getCode(), rootMessage(e));
        log.info(JSON.toJSONString(result));
        return result;
    }

    private String rootMessage(Exception ex) {
        Throwable rootCause = NestedExceptionUtils.getRootCause(ex);
        return rootCause != null ? rootCause.getMessage() : ex.getMessage();
    }

    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public ErrorResult handleBaseException(BaseException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(e.getErrCode());
        ErrorResult result = new ErrorResult(e.getErrCode(), e.getMessage());
        log.info(JSON.toJSONString(result));
        return result;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ErrorResult validationBodyException(MethodArgumentNotValidException exception) {
        ErrorResult commonResult = new ErrorResult();
        commonResult.setCode(HttpStatus.SC_BAD_REQUEST);
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();

            for (ObjectError objectError : errors) {
                FieldError fieldError = (FieldError) objectError;
                if (fieldError != null) {
                    log.error("Data check failure : object{" + fieldError.getObjectName() + "},field{" + fieldError.getField() +
                            "},errorMessage{" + fieldError.getDefaultMessage() + "}");
                    commonResult.setMsg(fieldError.getField() + fieldError.getDefaultMessage());
                    commonResult.setMessage(commonResult.getMsg());
                    return commonResult;
                }
            }
        }
        commonResult.setMsg("参数非法，请重试!");
        return commonResult;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ErrorResult handleException(Exception e) {
        log.error("系统异常", e);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(HttpStatus.SC_OK);
        ErrorResult result = new ErrorResult();
        result.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        result.setMsg("系统异常, 请联系管理员。");
        result.setMessage(result.getMsg());
        return result;
    }

    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public ErrorResult handleException(ValidationException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        ErrorResult commonResult = new ErrorResult();
        commonResult.setMsg(e.getMessage());
        commonResult.setCode(HttpStatus.SC_BAD_REQUEST);
        commonResult.setMessage(commonResult.getMsg());
        return commonResult;
    }

    /**
     * 针对测试环境k8s的健康检查，三次握手只会请求第一次就丢弃掉session，这个异常需要修改为手动返回成text类型
     *
     * @param e
     * @throws IOException
     */
    @ExceptionHandler(ClientAbortException.class)
    public void handleClientAbortException(ClientAbortException e) {
    }
}
